package hivi.vn.hivigold.fragment;

import hivi.vn.hivigold.R;
import hivi.vn.hivigold.activities.PartnerEditor;
import hivi.vn.hivigold.activities.PartnerHistory;
import hivi.vn.hivigold.adapters.PartnerAdapter;
import hivi.vn.hivigold.adapters.PartnerLoader;
import hivi.vn.hivigold.database.WebService;
import hivi.vn.hivigold.objects.Partner;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.LoaderManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.Loader;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;

public class PartnerFragment extends Fragment implements
		LoaderCallbacks<ArrayList<Partner>> {
	static final int LOADER_ID = 5;
	public final int REQUEST_EDITOR = 2;

	PartnerAdapter adapter;
	SearchView sv;
	PartnerListener pl;
	PartnerLoader loader;
	ListView lstPartner;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View v = inflater.inflate(R.layout.partners_layout, null);
		lstPartner = (ListView) v.findViewById(R.id.lstPartners);
		sv = (SearchView) v.findViewById(R.id.txtSearchPartner);
		Button btnSearch = (Button) v.findViewById(R.id.btnSearch);
		Button btnNew = (Button) v.findViewById(R.id.btnNew);

		adapter = new PartnerAdapter(getActivity(), null);
		lstPartner.setAdapter(adapter);
		lstPartner.setOnItemClickListener(onItemClick);
		lstPartner.setOnItemLongClickListener(onLong);
		getLoaderManager().initLoader(LOADER_ID, null, this);
		btnSearch.setOnClickListener(onClick);
		btnNew.setOnClickListener(onClick);
		return v;
	}

	void hideKeyboard() {
		InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
		if (imm != null)
			imm.hideSoftInputFromWindow(sv.getWindowToken(), 0);
	}
	
	OnItemLongClickListener onLong = new OnItemLongClickListener() {

		@Override
		public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
				int arg2, long arg3) {
			// TODO Auto-generated method stub
			final int position = arg2;
			AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
			builder.setTitle(R.string.choose);
			builder.setItems(R.array.editor_option,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							final Partner p = (Partner) adapter
									.getItemDirectly(position);
							dialog.dismiss();
							if (which == 0) {
								Intent i = new Intent(getActivity(),
										PartnerEditor.class);
								Bundle b = new Bundle();
								b.putInt(PartnerEditor.ACTION_KEY,
										PartnerEditor.ACTION_EDIT);
								b.putSerializable(PartnerEditor.DATA_REFERENCE,
										p);
								i.putExtras(b);
								startActivityForResult(i, REQUEST_EDITOR);
							} else if (which == 1) {
								AlertDialog.Builder builder = new AlertDialog.Builder(
										getActivity());
								builder.setTitle(R.string.confirm);
								builder.setMessage(R.string.confirm_ask);
								builder.setNegativeButton(R.string.btn_ok,
										new DialogInterface.OnClickListener() {
											@Override
											public void onClick(
													DialogInterface dialog,
													int which) {
												// TODO Auto-generated method
												// stub
												dialog.dismiss();
												PartnerTask delete = new PartnerTask();
												delete.execute(p);
											}
										});
								builder.setPositiveButton(R.string.btn_cancel,
										new DialogInterface.OnClickListener() {
											@Override
											public void onClick(
													DialogInterface dialog,
													int which) {
												// TODO Auto-generated method
												// stub
												dialog.dismiss();
											}
										});
								builder.create().show();
							} else if (which == 2) {
								Intent i = new Intent(getActivity(), PartnerHistory.class);
								Bundle b = new  Bundle();
								b.putSerializable(PartnerHistory.PARTNERSELECTED,p);
								i.putExtras(b);
								startActivityForResult(i, 1);
							}
						}
					});
			AlertDialog alert = builder.create();
			alert.show();
			return false;
		}

	};

	OnItemClickListener onItemClick = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			// TODO Auto-generated method stub
			if (pl != null) {
				Partner p = (Partner) adapter.getItem(arg2);
				pl.partnerSelected(p);
			}
		}

	};

	public void setListener(PartnerListener pl) {
		this.pl = pl;
	}

	OnClickListener onClick = new OnClickListener() {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if (v.getId() == R.id.btnSearch) {
				hideKeyboard();
				getLoaderManager().getLoader(LOADER_ID).onContentChanged();
			} else if (v.getId() == R.id.btnNew) {
				Intent i = new Intent(getActivity(), PartnerEditor.class);
				Bundle b = new Bundle();
				b.putInt(PartnerEditor.ACTION_KEY, PartnerEditor.ACTION_NEW);
				i.putExtras(b);
				startActivityForResult(i, REQUEST_EDITOR);
			}
		}
	};

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == getActivity().RESULT_OK) {
			loader.onContentChanged();
		}
	};

	/*
	 * @Override public boolean onContextItemSelected(MenuItem item) { // TODO
	 * Auto-generated method stub
	 * 
	 * AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
	 * .getMenuInfo();
	 * 
	 * if (item.getTitle().toString()
	 * .equals(getResources().getString(R.string.btn_edit))) {
	 * 
	 * } else {
	 * 
	 * } return true; }
	 */

	private class PartnerTask extends AsyncTask<Partner, Void, Boolean> {
		ProgressDialog dialog;

		@Override
		protected void onPostExecute(Boolean result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (result) {
				Toast.makeText(getActivity(),
						R.string.alert_delete_partner_success,
						Toast.LENGTH_LONG).show();
				loader.onContentChanged();
				registerForContextMenu(lstPartner);
			} else {
				Toast.makeText(getActivity(),
						R.string.alert_delete_partner_error, Toast.LENGTH_LONG)
						.show();
			}
			dialog.dismiss();
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			dialog = new ProgressDialog(getActivity());
			dialog.setMessage(getResources().getString(R.string.alert_waiting));
			dialog.show();
		}

		@Override
		protected Boolean doInBackground(Partner... p) {
			// TODO Auto-generated method stub
			return WebService.deletePartner(getActivity(), p[0].getPartnerID());
		}
	}

	/*
	 * @Override public void onCreateContextMenu(ContextMenu menu, View v,
	 * ContextMenuInfo menuInfo) { // TODO Auto-generated method stub
	 * super.onCreateContextMenu(menu, v, menuInfo);
	 * menu.add(R.string.btn_edit); menu.add(R.string.btn_delete); }
	 */

	@Override
	public Loader<ArrayList<Partner>> onCreateLoader(int arg0, Bundle arg1) {
		// TODO Auto-generated method stub
		loader = new PartnerLoader(getActivity(), sv);
		return loader;
	}

	@Override
	public void onLoadFinished(Loader<ArrayList<Partner>> arg0,
			ArrayList<Partner> arg1) {
		// TODO Auto-generated method stub
		adapter.swaper(arg1);

	}

	@Override
	public void onLoaderReset(Loader<ArrayList<Partner>> arg0) {
		// TODO Auto-generated method stub
		if (adapter != null) {
			adapter.swaper(null);
		}
	}

	public interface PartnerListener {
		public void partnerSelected(Partner p);
	}
}
